package cn.doctor.assistant.pad.ui.common;

import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.List;

import cn.doctor.assistant.pad.R;

/**
 * Created by jiaolf on 2016/4/5.
 */
public class ImageGridAdapter extends BaseAdapter {

    private Context context;
    private List<String> files;
    private GridView gridView;
    //item的宽和高
    private int itemWidth, itemHeight;

    private boolean isDone;
    public void setDone(boolean isDone) {
        this.isDone = isDone;
    }

    public ImageGridAdapter(Context context, List<String> files) {
        this.context = context;
        this.files = files;
    }

    public void setGridView(GridView gridView) {
        this.gridView = gridView;
    }

    @Override
    public int getCount() {
        return isDone ? files.size() : files.size() + 1;
    }

    @Override
    public Object getItem(int position) {
        return files.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private void setItemWidthAndHeight(int w, int h){
        itemWidth = (w - 30) / 3;
        itemHeight = (h - 50) / 3;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(gridView != null && itemHeight == 0 || itemWidth == 0){
            int w = gridView.getWidth();
            int h = gridView.getHeight();
            if(h != 0) setItemWidthAndHeight(w, h);
        }

        ImageView image = (ImageView) LayoutInflater.from(context).inflate(R.layout.image, null);
        // 最后一项为上传图片的操作(若已保存，则不显示)
        if (!isDone && position == files.size()) {

            image.setImageResource(R.drawable.add);
            image.setBackgroundResource(R.drawable.gridview_item_addbg);

        } else {

            String filePath = files.get(position);
            if (filePath.startsWith("http://")) {
                Picasso.with(context).load(filePath).into(image);
            } else {
                File file = new File(filePath);
                Uri uri = Uri.fromFile(file);
                image.setImageURI(uri);
            }

        }

        GridView.LayoutParams params = new GridView.LayoutParams(GridLayout.LayoutParams.FILL_PARENT, itemHeight);
        if(itemHeight != 0) {
            image.setLayoutParams(params);
        }

        return image;
    }
}
